import React, {useEffect, useState} from 'react';
import {Button, Form, Input, message, Modal, Select} from 'antd';
import {UploadView, upParams} from "@/components/FileUpload";

const FormItem = Form.Item;
const {Option} = Select;

const formLayout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 13,
  },
};

const UpdateForm = (props) => {
  const [form] = Form.useForm();
  const {
    onSubmit: handleUpdate,
    onCancel: handleUpdateModalVisible,
    updateModalVisible,
    values,
    platDomain,
    ossUrl
  } = props;

  const [logoUrl, setLogoUrl] = useState(values?.siteLogo);
  const [iconUrl, setIconUrl] = useState(values?.favicon);

  useEffect(async () => {
    const {siteLogo, favicon} = values;
    if (!siteLogo)
      setLogoUrl(siteLogo);
    if (!favicon)
      setIconUrl(favicon);
  }, []);

  const beforeUp = (file) => {
    const isGt50K = file.size / 1024 > 100;
    if (isGt50K) {
      return message.error('logo大小不能超过100k').then(() => false);
    }

    return true;
  };

  const handleChange = (info, type) => {
    const {file: {status, response}} = info;

    if (status === 'done') {
      message.success(`上传成功！`, 1).then(() => {
        const {data: {url, path}} = response;
        if (type === 'logo') {
          setLogoUrl(url ?? undefined);
          if (path)
            form.setFieldsValue({siteLogo: path ?? ''});
        } else {
          setIconUrl(url ?? undefined);
          if (path)
            form.setFieldsValue({favicon: path ?? ''});
        }

      });
    } else if (status === 'error') {
      message.error(`上传失败！`, 2).then(()=>{});
    }
  };

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    const value = {...values, ...fieldsValue};
    handleUpdate(value);
  };

  const renderContent = () => {
    return (
      <>
        <FormItem
          name="siteName"
          label="网站名称"
          rules={[
            {
              required: true,
              message: '网站名称为必填项',
            },
            {
              max: 50,
              type: 'string',
              message: '最多50个字',
            },
          ]}
        >
          <Input placeholder="请输入，不能为空，最多50个字！"/>
        </FormItem>
        <FormItem
          name="siteDomain"
          label="网站域名"
          rules={[
            {
              required: true,
              message: '域名为必填项',
            },
            {
              max: 50,
              type: 'string',
              message: '最多50位',
            },
          ]}
        >
          <Input placeholder="请输入域名，不能为空，最多50位！"/>
        </FormItem>
        <Form.Item label="个性域名">
          <Input.Group compact>
            <span>
            <Form.Item
              noStyle
              name="secondDomain"
              rules={[
                {
                  required: true,
                  message: '个性域名为必填项',
                },
                {
                  max: 10,
                  type: 'string',
                  message: '最多10位',
                },
                {
                  type: 'string',
                  pattern: '^[a-z]+$',
                  message: '只能是小写字母'
                }
              ]}
            >
              <Input
                style={{
                  width: 'calc(100% - 100px)',
                }}
                placeholder="请输入个性域名，不能为空！"
              />
            </Form.Item>
            .{platDomain}</span>
          </Input.Group>
        </Form.Item>
        <FormItem label="logo">
          <Input.Group compact>
            <span>
            <Form.Item
              style={{
                width: 'calc(100% - 100px)',
              }}
              name="siteLogo"
            >
              <Input hidden/>
            </Form.Item>
            <UploadView buttonTitle="点此上传" src={logoUrl} params={{...upParams(), accept: '.jpg,.png,.gif,.jpeg,.bmp,.svg,.svg+xml'}}
                        beforeUp={(file) => beforeUp(file)}
                        onChange={(info) => handleChange(info, 'logo')} />
            </span>
          </Input.Group>
        </FormItem>
        <FormItem label="favicon">
          <Input.Group compact>
            <span>
            <Form.Item
              style={{
                width: 'calc(100% - 100px)',
              }}
              name="favicon"
            >
              <Input hidden/>
            </Form.Item>
            <UploadView buttonTitle="点此上传" src={iconUrl} params={{...upParams(), accept: '.jpg,.png,.gif,.jpeg,.bmp,.svg,.x-icon,.ico,.svg+xml'}}
                        beforeUp={(file) => beforeUp(file)}
                        onChange={(info) => handleChange(info, 'icon')} />
            </span>
          </Input.Group>
        </FormItem>
        <FormItem
          name="siteUrl"
          label="主页地址"
          rules={[
            {
              required: true,
              message: '主页地址为必填项',
            },
            {
              max: 200,
              type: 'string',
              message: '最多200位',
            },
          ]}
        >
          <Input placeholder="请输入主页地址！"/>
        </FormItem>
        <FormItem
          name="siteTitle"
          label="网站标题"
          rules={[
            {
              required: true,
              message: '网站标题为必填项',
            },
            {
              max: 50,
              type: 'string',
              message: '最多50个字',
            },
          ]}
        >
          <Input placeholder="请输入网站标题！"/>
        </FormItem>
        <FormItem
          name="siteKeyword"
          label="关键词"
          rules={[
            {
              required: true,
              message: '关键词为必填项',
            },
            {
              max: 50,
              type: 'string',
              message: '最多125个字',
            },
          ]}
        >
          <Input placeholder="请输入关键词！"/>
        </FormItem>
        <FormItem
          name="siteDescription"
          label="网站描述"
          rules={[
            {
              required: true,
              message: '网站描述为必填项',
            },
            {
              max: 125,
              type: 'string',
              message: '最多125个字',
            },
          ]}
        >
          <Input placeholder="请输入网站描述！"/>
        </FormItem>
        <FormItem
          name="slogan"
          label="网站口号"
          rules={[
            {
              max: 25,
              type: 'string',
              message: '最多25个字',
            },
          ]}
        >
          <Input placeholder="请输入网站口号！"/>
        </FormItem>
        <FormItem
          name="displayOrder"
          label="展示顺序"
          rules={[
            {
              required: true,
              message: '展示顺序1~100！',
              pattern: '^([1-9]|[1-9]\\d|100)$',
              max: 3,
            },
          ]}
        >
          <Input placeholder="请输入数字"/>
        </FormItem>
        <FormItem name="isValid" label="状态">
          <Select
            style={{
              width: '100%',
            }}
          >
            <Option value="1">有效</Option>
            <Option value="0">无效</Option>
          </Select>
        </FormItem>
        <FormItem
          name="cnameDomain"
          label="别名域名"
          rules={[
            {
              required: false,
              message: '别名域名为必填项',
            },
            {
              max: 50,
              type: 'string',
              message: '最多50个字符',
            },
          ]}
        >
          <Input placeholder="多个别名，以半角逗号间隔"/>
        </FormItem>
        <FormItem
          name="foot"
          label="底部栏目"
        >
          <Input.TextArea rows={4} />
        </FormItem>
        <FormItem
          name="flink"
          label="友情链接"
        >
          <Input.TextArea rows={4} />
        </FormItem>
        <FormItem
          name="copy"
          label="版权信息"
        >
          <Input.TextArea rows={4} />
        </FormItem>
      </>
    );
  };

  const renderFooter = () =>
    (
      <>
        <Button onClick={() => handleUpdateModalVisible(false, values)}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>提交</Button>
      </>
    );

  return (
    <Modal
      width={640}
      bodyStyle={{
        padding: '32px 40px 48px',
      }}
      destroyOnClose
      title="域名配置"
      visible={updateModalVisible}
      footer={renderFooter()}
      onCancel={() => handleUpdateModalVisible()}
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          siteName: values.siteName,
          siteDomain: values.siteDomain,
          siteLogo: values.siteLogo?.indexOf(ossUrl) > -1 ? values.siteLogo.substring(ossUrl.length, values.siteLogo.length) : '',
          favicon: values.favicon?.indexOf(ossUrl) > -1 ? values.favicon.substring(ossUrl.length, values.favicon.length) : '',
          secondDomain: values.secondDomain,
          siteUrl: values.siteUrl,
          siteTitle: values.siteTitle,
          siteKeyword: values.siteKeyword,
          siteDescription: values.siteDescription,
          slogan: values.slogan,
          isValid: values.isValid,
          displayOrder: values.displayOrder,
          cnameDomain: values.cnameDomain,
          foot: values.foot,
          flink: values.flink,
          copy: values.copy
        }}
      >
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default UpdateForm;
